package com.tuyrt.windy.ui.place

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.tuyrt.windy.R
import com.tuyrt.windy.logic.model.Place
import com.tuyrt.windy.ui.weather.WeatherActivity

/**
 * Created by tuyrt7 on 2021/4/14.
 */
class PlaceAdapter(private val fragment: PlaceFragment, private val placeList: List<Place>) :
    RecyclerView.Adapter<PlaceAdapter.ViewHolder>() {

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val placeName: TextView = itemView.findViewById(R.id.placeName)
        val placeAddress: TextView = itemView.findViewById(R.id.placeAddress)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.place_item, parent, false)

        val holder = ViewHolder(itemView)
        holder.itemView.setOnClickListener {
            val place = placeList[holder.adapterPosition]
            val activity = fragment.activity
            if (activity is WeatherActivity) {
                //如果在天气页面，刷新数据就行
                activity.binding.drawerLayout.closeDrawers()
                activity.viewModel.locationLat = place.location.lat
                activity.viewModel.locationLng = place.location.lng
                activity.viewModel.placeName = place.name
                activity.refreshWeather()
            } else {
                fragment.startActivity(Intent(parent.context, WeatherActivity::class.java).apply {
                    putExtra("location_lat", place.location.lat)
                    putExtra("location_lng", place.location.lng)
                    putExtra("place_name", place.name)
                })
                fragment.activity?.finish()
            }
            fragment.viewModel.savePlace(place)
        }
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = placeList[position]
        holder.placeName.text = place.name
        holder.placeAddress.text = place.address
    }

    override fun getItemCount(): Int = placeList.size
}